package com.gooluke.shorten.strategy;

import com.gooluke.shorten.context.GenerateContext;
import com.gooluke.shorten.util.Base62;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.util.HexFormat;

/**
 * md5算法生成短链
 */
@Component
@ConditionalOnProperty(name = "shorten.strategy", havingValue = "hash")
public class MD5Strategy implements ShortCodeStrategy {

    private static final HexFormat HEX_FORMAT = HexFormat.of();
    private static final int CODE_LENGTH = 8;// 短链长度

    @Override
    public String generate(String originalUrl, GenerateContext context) {
        try {
            // 组合用户ID和原始URL降低碰撞概率
            String input = originalUrl + (context.getCreator() != null ? context.getCreator() : "");
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes());
            String hex = HEX_FORMAT.formatHex(digest);

            // 取前10字符并转换为Base62
            return hex.substring(0, 10)
                    .chars()
                    .map(c -> c % 62)
                    .collect(StringBuilder::new,
                            (sb, i) -> sb.append(Base62.CHAR_SET[i]),
                            StringBuilder::append)
                    .substring(0, CODE_LENGTH);
        } catch (Exception e) {
            throw new RuntimeException("MD5生成失败", e);
        }
    }
}